package com.example.sdbtspringboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;


import com.example.sdbtspringboot.entity.User;
import com.example.sdbtspringboot.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.jta.JtaAfterCompletionSynchronization;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;



/**
 * @Description: token工具类
 * @Author: cao
 * @Date: 2024/5/29 9:35
 */
@Component
public class TokenUtils {

    private static UserMapper staticUserMapper;

    @Resource
    UserMapper userMapper;

    @PostConstruct
    public void setStaticUserMapper(){
        staticUserMapper=userMapper;
    }

    /*
    * 生成token
    *
    * @retrun
    */
    public static String genToken(String userId,String sign){
        return JWT.create().withAudience(userId)//user id保存到token里作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时token过期
                .sign(Algorithm.HMAC256(sign));//密钥格式

    }
    /*
     * 获取当前用户登录信息
     *
     * @retrun user对象
     */
    public static User getcurrentUser(){
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token=request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String userId= JWT.decode(token).getAudience().get(0);
                return staticUserMapper.selectByid(Integer.valueOf(userId));
            }

        }catch (Exception e){
            return null;
        }
        return null;
    }
}
